package com.hcloud.upload

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.UriUtils
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.hcloud.libupload.callback.ICreateTaskCallback
import com.hcloud.libupload.callback.IPartSuccessCallback
import com.hcloud.libupload.callback.IProgressCallback
import com.hcloud.libupload.comom.UploadClient
import com.hcloud.libupload.comom.UploadConfig
import com.hcloud.libupload.comom.UploadLib
import com.hcloud.libupload.http.Progress
import com.hcloud.libupload.request.UploadRequest
import java.util.*

class MainActivity : AppCompatActivity() {


    var uploadClient: UploadClient? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        val uploadConfig =
                UploadConfig.Builder()
                        .setLoginKey("5MW639Yeym5coP43PjTFwULm+jz7ROqMpYtKt+Pq5gk=")
                        .setPhone("18000000541")
                        .setBoxId("m10C2u0541")
                        .setUpNode("http://192.168.1.250:8881")
                        .setSdkType(0)
                        .setMainNode("http://192.168.1.201/")
                        .setMaxUploadPart(3)
                        .setMaxUploadTask(2)
                        .setFastUpload(false)
                        .build()
        UploadLib.instance().init(uploadConfig)


        uploadClient = UploadClient()

        PermissionUtils.permission(PermissionConstants.STORAGE)
                .callback(object : PermissionUtils.SimpleCallback {

                    override fun onGranted() {
                        start()
                    }

                    override fun onDenied() {
                    }
                })
                .request()


    }

    fun start() {
        findViewById<FloatingActionButton>(R.id.fl_upload).setOnClickListener {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type = "*/*"
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            //intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
            startActivityForResult(intent, 1000)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
            if (data!!.data != null) {
                val uri = data.data
                val filePath = uri.toString()
                Log.d("upload--sdk", "path:$filePath")
                startUpload(filePath)
            } else {
                val clipData = data.clipData
                if (clipData != null) {
                    val pathList: ArrayList<String> = ArrayList()
                    for (i in 0 until clipData.itemCount) {
                        val item = clipData.getItemAt(i)
                        val uri = item.uri
                        val filePath = uri.toString()
                        pathList.add(filePath)
                    }
                }
            }
        }
    }


    private fun startUpload(uri: String) {


        val file = UriUtils.uri2File(Uri.parse(uri))

        LogUtils.i("----${file.name}------${file.path}")

        val uploadRequest = UploadRequest(filePath = file.path, serverPath = "/shared/")

        findViewById<TextView>(R.id.tv_name).text = file.name

        var isPause = false
        findViewById<View>(R.id.bt_pause).setOnClickListener {
            if (isPause) {
                Log.d("YiLog","rquestId1:"+uploadRequest.requestId)
                findViewById<Button>(R.id.bt_pause).text ="暂停"
                startUpload(uploadRequest)
            } else {
                Log.d("YiLog","rquestId2:"+uploadRequest.requestId)
                findViewById<Button>(R.id.bt_pause).text ="继续"
                uploadRequest.cancel()
            }
            isPause = !isPause
        }

        startUpload(uploadRequest)
    }

    private fun startUpload(uploadRequest: UploadRequest) {
        uploadClient?.upload(uploadRequest, object : ICreateTaskCallback {
            override fun createSuccess(request: UploadRequest) {
                Log.d("YiLog", "createSuccess: " + request.filePath)
            }

            override fun createError(
                    uploadRequest: UploadRequest,
                    errorCode: String,
                    errorMsg: String
            ) {
                Log.d("YiLog", "createError: " + uploadRequest.filePath)
            }
        })
        uploadRequest.setProgressCallback(object : IProgressCallback {
            override fun progress(uploadRequest: UploadRequest, progress: Progress) {
                Log.d("YiLog", "progress:" + progress.progress)
            }

            override fun success(uploadRequest: UploadRequest) {
                Log.d("YiLog", "--------success---------")
            }

            override fun error(uploadRequest: UploadRequest, errorCode: String, errorMsg: String) {
                Log.d("YiLog", "--------error---------$errorCode $errorMsg")
            }
        })

        uploadRequest.setPartSuccessCallback(object : IPartSuccessCallback {
            override fun partSuccess(uploadRequest: UploadRequest, progress: Progress) {
                Log.d("YiLog", "uploadRequest_part:" + uploadRequest.part)
            }
        })
    }


}